package com.fingard.dsp.bank.directbank.nnbill01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.nnbill01.wsdl.balancedetail.*;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.AESHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import org.apache.commons.codec.binary.Base64;

import java.util.Calendar;
import java.util.Date;

public class NNBill01Transaction extends NNBill01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req7516.actNum, "balDetail");

            if (actItem == null) {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo("未找到账号[" + p_req7516.actNum + "]商户配置信息");
                retAts.writeEnd();
                return retAts;
            }
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;

            // 按天查询
            while (tmpIntDateFrom <= tmpIntDateTo) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());

                // 判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    // 跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                String pageNo = "";
                int pageCount = 1;

                pageNo = String.format("%s", pageCount).replace(" ", "0");
                Version version = new Version();
                version.setVersion("1");
                version.setService("ma.mbrinfo.balancedetail");

                MaMbrinfoRequestHead reqHeader = new MaMbrinfoRequestHead();
                reqHeader.setVersion(version);
                reqHeader.setAppId("");
                reqHeader.setRequestId("");

                DetailApiRequestType deApiReqType = new DetailApiRequestType();
                deApiReqType.setRequestTime(Format.DateTime14Format.format(new Date()));
                deApiReqType.setStartTime(Format.DateTime14Format.format(tmpCalendarFrom.getTime()));
                deApiReqType.setEndTime(Format.DateTime14Format.format(tmpCalendarTo.getTime()));
                deApiReqType.setMemberCode(actItem.merchantId);
                String memberAcctID = getBankConfig().getValueAsString("memberAcctCode7516");
                deApiReqType.setMbrAcctCode(memberAcctID);
                deApiReqType.setPageNo(pageNo);
                deApiReqType.setPageSize("100");
                new MaSealPkiDataType();


                String saltKey = actItem.saltKey;
                String featureCode7516 = getBankConfig().getValueAsString("featureCode7516");
                String originalData = "";
                if (StringHelper.hasAnyChar(saltKey) && StringHelper.hasAnyChar(featureCode7516)) {
                    originalData = requestOriginalData(deApiReqType, saltKey);
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("请求报文中key节点或featureCode节点为空，请检查NNBill01/config.xml中'key','featureCode'节点配置");
                    return retAts;
                }

                WriteBankLogLn("请求数据：" + originalData);
                byte[] originalBytes = originalData.replace("\"", "").getBytes(getCharset());
                byte[] randomBytes = randomKey();

                // 签名
                byte[] signBytes = signByRSA(originalBytes, actItem);
                String signData = Base64.encodeBase64String(signBytes);

                // 加密
                String encryptData = AESHelper.encodeAES(randomBytes, originalBytes);

                // 数字信封
                byte[] digitalBytes = encryptByPKRSA(randomBytes,actItem);
                String digitalData = Base64.encodeBase64String(digitalBytes);

                /**
                 * 请求体
                 * 		-- 加密数据
                 */
                MaSealPkiDataType pkiReqType = new MaSealPkiDataType();

                // 原始数据（证书方式没数据）
                pkiReqType.setOriginalData("");

                // 报文签名
                pkiReqType.setSignedData(signData);
                // 报文加密
                pkiReqType.setEncryptedData(encryptData);
                // 报文数字信封
                pkiReqType.setDigitalEnvelope(digitalData);
                WriteBankLogLn("signData：" + signData + "encryptData：" + encryptData + "digitalData：" + digitalData);
                BalanceDetailRequestBody requestBody = new BalanceDetailRequestBody();
                requestBody.setDetailApiRequestType(deApiReqType);
                requestBody.setMaSealPkiDataType(pkiReqType);
                BalanceDetailRequest request = new BalanceDetailRequest();
                request.setRequestBody(requestBody);
                request.setRequestHeader(reqHeader);
                BalanceDetailResponse response = balanceDetailFormWS(request);
                /**
                 * 响应头
                 */
                MaMbrinfoResponseHead respHeader = response.getResponseHeader();

                // 交易状态码
                String backErrorCode = respHeader.getErrorCode();
                // 交易返回信息
                String backErrorMsg = respHeader.getErrorMsg();


                if (backErrorCode.equals("1000")) {
                    /**
                     * 响应体
                     */
                    BalanceDetailResponseBody respBody = response.getResponseBody();

                    /**
                     * 响应体
                     * 		-- 加密数据
                     */
                    MaSealPkiDataType pkiRespType = respBody.getMaSealPkiDataType();

                    // 返回签名
                    String backSignData = pkiRespType.getSignedData();
                    // 返回数字信封
                    String backDigitalData = pkiRespType.getDigitalEnvelope();
                    // 返回加密数据
                    String backEncryptData = pkiRespType.getEncryptedData();
                    WriteBankLogLn("backSignData：" + backSignData + "\nbackEncryptData：" + backEncryptData + "\nbackDigitalData：" + backDigitalData);

                    byte[] backSignBytes = Base64.decodeBase64(backSignData);
                    byte[] backencryptBytes = Base64.decodeBase64(backEncryptData);
                    byte[] backDigitalBytes = Base64.decodeBase64(backDigitalData);

                    // 解密数字信封
                    byte[] backKey = decryptByPKRSA(backDigitalBytes, actItem);
                    // 返回原文
                    byte[] backOriginalBytes = AESHelper.decodeAES(backKey, backencryptBytes);
                    // 验签结果
                    boolean verifyResult = verifyByRSA(backOriginalBytes, backSignBytes, actItem);

                    // 验签处理
                    if (verifyResult == true) {
                        // 返回响应数据
                        DetailApiResponseType detailApiResponseType = response.getResponseBody().getDetailApiResponseType();
                        String  requestOriginalData= responseOriginalData(detailApiResponseType, saltKey);
                        WriteBankLogLn("请求原数据："+ requestOriginalData);
                        DetailListType[] detailList = detailApiResponseType.getDetailList();
                        if (detailList != null) {
                            RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                            for(int i = 0; i < detailList.length; ++i) {
                                tmpRetDetail.tranTime = detailList[i].getOrderTime();//交易时间
                                tmpRetDetail.seqId = detailList[i].getOrderseqId();//快钱交易号
                                tmpRetDetail.reqBatchNO = detailList[i].getBatchId();//批次号
                                tmpRetDetail.askNumber = detailList[i].getMerchantId();//商家订单号
                                String tranAmt = detailList[i].getIncome();
                                if (StringHelper.hasAnyChar(tranAmt)) {
                                    tmpRetDetail.cdFlag = "1";
                                    tmpRetDetail.recAccBank = detailList[i].getBank();//交易对方银行名称
                                    tmpRetDetail.recAccName = detailList[i].getName();//交易对方户名
                                    tmpRetDetail.recAccNum = detailList[i].getBankcardNo();//交易对方卡号
                                    tmpRetDetail.tranAmt = tranAmt;
                                } else {
                                    tranAmt = detailList[i].getPay();
                                    tmpRetDetail.cdFlag = "2";
                                    tmpRetDetail.recAccBank = detailList[i].getBank();//交易对方银行名称
                                    tmpRetDetail.recAccName = detailList[i].getName();//交易对方户名
                                    tmpRetDetail.recAccNum = detailList[i].getBankcardNo();//交易对方卡号
                                    tmpRetDetail.tranAmt = tranAmt;
                                }
                                tmpRetDetail.accBal = detailList[i].getBalance();//余额
                                tmpRetDetail.abstr = detailList[i].getRemark();//备注
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                            pageCount++;
                        } else {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo("detailList对象为空");
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo("验签失败!");
                    }

                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(backErrorMsg);
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(ex.getMessage());
            WriteBankLogLn(ex);
        }

        /*if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }*/
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        return null;
    }
}
